import React, { FC, useState } from "react";
import { useRequest, useTitle } from "ahooks";
import styles from "../index.module.scss";
import {
  Empty,
  Typography,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Spin,
  message,
} from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import ListSearch from "../../../components/ListSearch";
import useLoadQuestionListData from "../../../hooks/useLoadQuestionListData";
import ListPage from "../../../components/ListPage";
import { deleteQuestionService, updateQuestionListService } from "../../../service/questions";
import { QuestionType } from "../../../components/QuestionCard";

const { Title } = Typography;
const { confirm } = Modal;
const rawQuestionList = [
  {
    _id: "q1",
    title: "问卷1",
    isPublished: false,
    isStar: false,
    answerCount: 5,
    createdAt: "3月15日 12:11",
  },
  {
    _id: "q2",
    title: "问卷2",
    isPublished: true,
    isStar: true,
    answerCount: 1,
    createdAt: "3月10日 12:11",
  },
  {
    _id: "q3",
    title: "问卷3",
    isPublished: false,
    isStar: true,
    answerCount: 12,
    createdAt: "2月15日 12:11",
  },
  {
    _id: "q4",
    title: "问卷4",
    isPublished: true,
    isStar: false,
    answerCount: 5,
    createdAt: "3月30日 12:11",
  },
];
const Trash: FC = () => {
  useTitle("LUABU问卷 — 回收站");
  const { data = {}, loading, refresh  } = useLoadQuestionListData({ isDeleted: true });
  const { list = [], total = 0 } = data;

  const tableColumns = [
    {
      title: "标题",
      dataIndex: "title",
    },
    {
      title: "是否发布",
      dataIndex: "isPublished",
      render: (isPublished: boolean) => {
        return isPublished ? (
          <Tag color="processing">已发布</Tag>
        ) : (
          <Tag>未发布</Tag>
        );
      },
    },
    {
      title: "填写份数",
      dataIndex: "answerCount",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
    },
    {
      title: "操作",
      render: (q: QuestionType) => {
        return (
          <>
            <Space>
              <Button danger size="small" onClick={() => handleDelete(q)}>
                删除
              </Button>
              <Button size="small" onClick={() => handleRecover(q)}>恢复</Button>
            </Space>
          </>
        );
      },
    },
  ];

  //记录选中的id
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  //记录单个id
  // const [cardId, setCardId] = useState<string>('');

  //恢复
  const { run: recoverMore} = useRequest(async () => {
    for await (const id of selectedIds) {
      await updateQuestionListService(id, {isDeleted: false})
    }
  },
  {
    manual: true,
    debounceMaxWait: 1500,
    onSuccess() {
      message.success("恢复成功")
      
      refresh() //手动刷新
    }
  })
  //删除
  const {run: deleteQuestion} = useRequest(async () => await deleteQuestionService(selectedIds), {
    manual: true,
    debounceWait:1500,
    onSuccess() {
      message.success("删除成功")
      refresh()
      setSelectedIds([])
    }
  })
  //删除单个
  function handleDelete(question: QuestionType) {
    setSelectedIds(selectedIds.concat(question._id))
    confirm({
      title: "彻底删除问卷",
      icon: <ExclamationCircleOutlined />,
      content: "删除之后不可回复",
      okText: "确认",
      cancelText: "取消", 
      onOk: deleteQuestion
    })
  }
  //恢复单个
  const { run:recover } = useRequest( async (id: string) => {
    const data = await updateQuestionListService(id, { isDelete: false})
  },{
    manual: true,
    debounceMaxWait: 1500,
    onSuccess(){
      message.success("恢复成功")
      refresh()
      setSelectedIds([])
    }
  })
  function handleRecover(question: QuestionType) {
    recover(question._id)
  }

  function del() {
    confirm({
      title: "彻底删除该问卷",
      icon: <ExclamationCircleOutlined />,
      content: "删除之后不可回复",
      okText: "确认",
      cancelText: "取消",
      onOk: deleteQuestion
    });
  }
  const TableElem = (
    <>
      <div>
        <Space style={{ marginBottom: "12px" }}>
          <Button disabled={selectedIds.length === 0} onClick={recoverMore}>恢复</Button>
          <Button danger disabled={selectedIds.length === 0} onClick={del}>
            删除
          </Button>
        </Space>
      </div>
      <Table
        dataSource={list}
        columns={tableColumns}
        pagination={false}
        rowKey={(q) => q._id}
        rowSelection={{
          type: "checkbox",
          onChange: (selectedRowKeys) => {
            setSelectedIds(selectedRowKeys as string[]);
          },
        }}
      ></Table>
    </>
  );
  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {loading && (
          <div style={{ textAlign: "center" }}>
            <Spin></Spin>
          </div>
        )}
        {!loading && list.length === 0 && <Empty description="暂无问卷" />}
        {list.length > 0 && TableElem}
      </div>
      <div className={styles.footer}>
        <ListPage total={total}/>
      </div>
    </>
  );
};

export default Trash;
